package com.tomato.modules.user.controller;

import com.tomato.api.id.fegin.RemoteIdService;
import com.tomato.api.user.dataobject.AccountDO;
import com.tomato.api.user.dataobject.UserDO;
import com.tomato.api.user.vo.req.UserCreateReqVO;
import com.tomato.base.controller.controller.BaseController;
import com.tomato.base.core.constant.IdNameConstants;
import com.tomato.base.core.dto.SingleResponse;
import com.tomato.modules.user.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.validation.Valid;

/**
 * user
 *
 * @author lizhifu
 * @date 2022/4/1
 */
@RestController
@Slf4j
public class UserController extends BaseController {
    @Resource
    private UserService userService;
    @Resource
    private RemoteIdService remoteIdService;
    @Resource
    private PasswordEncoder passwordEncoder;
    @PostMapping("/api/user/createUser")
    public SingleResponse createUser(@Valid @RequestBody UserCreateReqVO vo) {
        // 获取用户id-分布式id
        SingleResponse<Long> response = remoteIdService.getId(IdNameConstants.TOMATO_MODULES_USER);
        if (!response.isSuccess()) {
            log.error("获取用户id失败，{}", response.getErrMessage());
            return SingleResponse.buildFailure(response.getErrCode(),"获取用户id失败");
        }
        // 创建用户和账号
        UserDO userPO = new UserDO();
        userPO.setUserId(response.getData());
        // 加密密码
        userPO.setPassword(passwordEncoder.encode(vo.getPassword()));

        AccountDO accountPO = new AccountDO();
        accountPO.setUserId(response.getData());
        accountPO.setLoginAccount(vo.getLoginAccount());

        userService.createUser(userPO, accountPO);

        // 返回用户id
        return SingleResponse.of(response.getData());
    }
}
